package cn.qingsec.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.util.SaResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 */
@RestControllerAdvice // 可指定包前缀，比如：(basePackages = "com.pj.admin")
public class GlobalException {

    // 全局异常拦截（拦截项目中的所有异常）
    @ExceptionHandler
    public SaResult handlerException(Exception e, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 打印堆栈，以供调试
        e.printStackTrace();
        if (e instanceof NotLoginException) {	// 如果是未登录异常
            NotLoginException ee = (NotLoginException) e;
            return SaResult.get(SaResult.CODE_ERROR,"未登录异常",ee.getMessage());
        } else if(e instanceof NotRoleException) {		// 如果是角色异常
            NotRoleException ee = (NotRoleException) e;
            return SaResult.get(SaResult.CODE_ERROR,"无此角色",ee.getRole());
        } else if(e instanceof NotPermissionException) {	// 如果是权限异常
            NotPermissionException ee = (NotPermissionException) e;
            return SaResult.get(SaResult.CODE_ERROR,"无此权限",ee.getPermission());
        } else {	// 普通异常, 输出：500 + 异常信息
            return SaResult.get(SaResult.CODE_ERROR,"ERROR",e.getMessage());

        }
    }
}
